<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';

const router = useRouter();

// 表格加载状态
const loading = ref(false);

// 助贷保障表格数据
const tableData = ref([]);

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 搜索条件
const searchForm = reactive({
  keyword: '',
  status: '',
  startTime: '',
  endTime: '',
  orderNo: ''
});

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '申请中', value: '0' },
  { label: '已通过', value: '1' },
  { label: '已拒绝', value: '2' }
];

// 模拟数据 - 助贷保
const mockData = [
  {
    id: '1',
    orderNo: 'AL20230501001',
    customerName: '张三',
    customerPhone: '13812345678',
    productName: '企业经营贷',
    applyAmount: 500000,
    approveAmount: 450000,
    applyTime: '2023-05-01 10:25:36',
    status: '1',
    salesUser: '李业务',
    loanStatus: '已放款',
    loanChannel: '招商银行',
    loanTime: '2023-05-10 15:30:45'
  },
  {
    id: '2',
    orderNo: 'AL20230502002',
    customerName: '李四',
    customerPhone: '13987654321',
    productName: '小微企业贷',
    applyAmount: 800000,
    approveAmount: 700000,
    applyTime: '2023-05-02 14:10:22',
    status: '1',
    salesUser: '王业务',
    loanStatus: '已放款',
    loanChannel: '工商银行',
    loanTime: '2023-05-12 09:45:30'
  },
  {
    id: '3',
    orderNo: 'AL20230503003',
    customerName: '王五',
    customerPhone: '13512345678',
    productName: '供应链贷款',
    applyAmount: 600000,
    approveAmount: 0,
    applyTime: '2023-05-03 09:30:15',
    status: '2',
    salesUser: '赵业务',
    loanStatus: '已拒绝',
    loanChannel: '',
    loanTime: ''
  },
  {
    id: '4',
    orderNo: 'AL20230504004',
    customerName: '赵六',
    customerPhone: '13612345678',
    productName: '设备贷款',
    applyAmount: 300000,
    approveAmount: 0,
    applyTime: '2023-05-04 16:45:33',
    status: '0',
    salesUser: '张业务',
    loanStatus: '审核中',
    loanChannel: '',
    loanTime: ''
  }
];

// 初始化数据
onMounted(() => {
  fetchData();
});

// 获取数据
const fetchData = () => {
  loading.value = true;
  setTimeout(() => {
    // 筛选助贷保数据
    let filteredData = [...mockData];

    // 关键词筛选
    if (searchForm.keyword) {
      filteredData = filteredData.filter(item =>
        item.customerName.includes(searchForm.keyword) ||
        item.customerPhone.includes(searchForm.keyword) ||
        item.productName.includes(searchForm.keyword)
      );
    }

    // 订单号筛选
    if (searchForm.orderNo) {
      filteredData = filteredData.filter(item =>
        item.orderNo.includes(searchForm.orderNo)
      );
    }

    // 状态筛选
    if (searchForm.status) {
      filteredData = filteredData.filter(item =>
        item.status === searchForm.status
      );
    }

    // 时间筛选
    if (searchForm.startTime && searchForm.endTime) {
      filteredData = filteredData.filter(item => {
        const applyTime = new Date(item.applyTime).getTime();
        const startTime = new Date(searchForm.startTime).getTime();
        const endTime = new Date(searchForm.endTime).getTime();
        return applyTime >= startTime && applyTime <= endTime;
      });
    }

    tableData.value = filteredData;
    total.value = filteredData.length;

    loading.value = false;
  }, 300);
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = '';
  searchForm.orderNo = '';
  searchForm.status = '';
  searchForm.startTime = '';
  searchForm.endTime = '';
  currentPage.value = 1;
  fetchData();
};

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchData();
};

// 处理每页数量变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchData();
};

// 格式化状态
const formatStatus = (row) => {
  switch (row.status) {
    case '0':
      return '申请中';
    case '1':
      return '已通过';
    case '2':
      return '已拒绝';
    default:
      return '未知状态';
  }
};

// 格式化金额
const formatAmount = (amount) => {
  return amount ? `¥${amount.toLocaleString()}` : '-';
};

// 查看订单详情
const viewOrderDetail = (row) => {
  router.push(`/business-manage/assist-loan/detail/${row.id}`);
};

// 查看订单操作记录
const viewOrderLog = (row) => {
  ElMessageBox.alert(
    `订单号：${row.orderNo}<br><br>
     <strong>操作记录:</strong><br>
     ${row.applyTime} - 用户提交申请 - 操作人：系统<br>
     ${row.applyTime.split(' ')[0]} 10:30:15 - 审核人员接单 - 操作人：张审核<br>
     ${row.status === '1' || row.status === '2' ?
      `${row.applyTime.split(' ')[0]} 14:25:30 - ${row.status === '1' ? '审核通过' : '审核拒绝'} - 操作人：李经理<br>` : ''}
     ${row.loanTime ? `${row.loanTime} - 完成放款 - 操作人：王出纳<br>` : ''}`,
    '操作记录',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确定'
    }
  );
};
</script>

<template>
  <div class="assist-loan-container">
    <!-- 搜索表单 -->
    <el-card shadow="never" class="filter-card">
      <el-form :inline="true" :model="searchForm" class="filter-form">
        <el-form-item>
          <el-input v-model="searchForm.keyword" placeholder="客户姓名/手机号/产品名称" clearable @keyup.enter="handleSearch"
            style="width: 220px">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-input v-model="searchForm.orderNo" placeholder="订单号" clearable @keyup.enter="handleSearch"
            style="width: 180px" />
        </el-form-item>

        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="审核状态" clearable style="width: 120px">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-date-picker v-model="searchForm.startTime" type="datetime" placeholder="开始时间" format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 180px" />
        </el-form-item>

        <el-form-item>
          <el-date-picker v-model="searchForm.endTime" type="datetime" placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 180px" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 内容区域 -->
    <el-card shadow="never" class="content-card">
      <template #header>
        <div class="card-header">
          <span>助贷保业务明细</span>
        </div>
      </template>

      <el-table :data="tableData" style="width: 100%" v-loading="loading" border
        :header-cell-style="{ background: '#f5f7fa' }">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="orderNo" label="订单号" min-width="140" show-overflow-tooltip />
        <el-table-column prop="customerName" label="客户姓名" width="100" align="center" />
        <el-table-column prop="customerPhone" label="联系电话" width="120" align="center" />
        <el-table-column prop="productName" label="产品名称" width="120" align="center" />
        <el-table-column label="申请金额" width="120" align="right">
          <template #default="scope">
            {{ formatAmount(scope.row.applyAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="批复金额" width="120" align="right">
          <template #default="scope">
            {{ formatAmount(scope.row.approveAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="applyTime" label="申请时间" width="160" align="center" />
        <el-table-column label="订单状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'info' : scope.row.status === '1' ? 'success' : 'danger'">
              {{ formatStatus(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="salesUser" label="业务员" width="100" align="center" />
        <el-table-column prop="loanChannel" label="放款渠道" width="120" align="center" />

        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewOrderDetail(scope.row)">详情</el-button>
            <el-button type="info" size="small" @click="viewOrderLog(scope.row)">订单记录</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          background layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handlePageChange" />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.assist-loan-container .filter-card {
  margin-bottom: 20px;
}

.assist-loan-container .filter-form {
  display: flex;
  flex-wrap: wrap;
}

.assist-loan-container .filter-form .el-form-item:last-child {
  margin-left: auto;
}

.assist-loan-container .content-card {
  margin-top: 20px;
}

.assist-loan-container .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.assist-loan-container .pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>